<template>
  <div class="article-list">
    <!-- PullRefresh 下拉刷新 -->
    <van-pull-refresh success-duration="1000" :success-text="refreshText" v-model="PRloading" @refresh="onRefresh">
      <!-- load事件 list初始化会触发，如果请求数据没有铺满页面 将二次触发 -->
      <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="getArticle">
        <!-- 使用article-time展示组件 -->
        <article-time v-for="article in list" :key="article.art_id" :article="article">
        </article-time>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { onActivated, onDeactivated, ref } from 'vue'
import { getArticleAPI } from '@/api/article'
import ArticleTime from '@/components/article-item/articleItem.vue'
export default {
  name: 'Atricle-list',
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  components: {
    ArticleTime
  },
  setup (props) {
    const list = ref([])// 列表数据
    const loading = ref(false)// 加载中状态
    const finished = ref(false)// 控制结束状态
    const timestamp = ref(null)// 存储下一页数据的时间戳
    const error = ref(false)// 控制列表加载失败提示状态
    const PRloading = ref(false)//  下拉刷新狀態
    const refreshText = ref('刷新成功')// 下拉刷新提示文本
    // 请求列表新闻
    const getArticle = async () => {
      const { data } = await getArticleAPI({
        channel_id: props.channel.id,
        // timestamp 请求新的推荐数据传当前的时间戳，请求历史推荐传指定的时间戳
        timestamp: timestamp.value || Date.now()
      })
      const { results } = data.data
      list.value.push(...results)
      // 加载中状态
      loading.value = false
      // 判断是否加载完所有数据
      if (results.length) {
        // 继续加载下一页数据
        timestamp.value = data.data.pre_timestamp
      } else {
        // 没有数据了 结束加载
        finished.value = true
      }
    }
    // 下拉刷新
    const onRefresh = async () => {
      try {
        const { data } = await getArticleAPI({
          channel_id: props.channel.id,
          timestamp: Date.now()
        })
        const { results } = data.data
        list.value.unshift(...data.data.results)
        // 关闭下拉刷新的loading
        PRloading.value = false
        refreshText.value = `刷新成功 更新了${results.length}条数据`
      } catch (err) {
        PRloading.value = false
        refreshText.value = '刷新失败'
      }
    }
    onActivated(() => {
      // console.log('onActivated')
    })
    onDeactivated(() => {
      // console.log('onDeactivated')
    })
    return {
      list,
      getArticle,
      loading,
      finished,
      timestamp,
      error,
      onRefresh,
      PRloading,
      refreshText
    }
  }
}
</script>

<style scoped lang="less">
// 让组件拥有自己的滚动容器，这样不同频道滚到就会形成记忆 不会相互印象
.article-list {
  height: 90vh;
  overflow-y: auto;
}
</style>
